import React, { Component } from 'react'
import classnames from 'classnames';
import { Icon } from 'weaver-mobile';
import '../style/index.less'

export default class Select extends Component {
  static defaultProps = {
    options: [],
    randomkey: `cr${Math.random().toString(36).substr(2, 6)}`,
    prefixCls: 'cr-select',
  }

  constructor(props) {
    super(props)
  
    this.state = {
      isActive: false,
    }
  }

  onChangeActive = () => {
    const { isActive } = this.state;
    this.setState({ isActive: !isActive })
  }

  getCurrentSelect = (value) => {
    const { options } = this.props
    if (!options || options.length < 1) return;

    let item = options.filter(o => o.key === value)[0]
    if (item) return item.showname
    else return ''
  }

  onChange = (option) => {
    const { onChange, value } = this.props
    this.setState({ isActive: false })
    if (value !== option.key) {
      onChange(option)
    }
  }

  render() {
    const { options, randomkey, className, value, prefixCls } = this.props
    const { isActive } = this.state
    const selectCls = classnames({
      [prefixCls]: true,
      [className]: className
    })
    const currentSelect = this.getCurrentSelect(value)
    return (
      <div className={selectCls}>
        <div className={`${prefixCls}-title`} onClick={this.onChangeActive}>
          <span>{currentSelect}</span>
          <span className={`${prefixCls}-title-icon`}><Icon type={isActive ? 'up' : 'down'} size='xxs'/></span>
        </div>
        <div className={`${prefixCls}-content`} style={{ display: isActive ? 'block' : 'none' }}>
          {options && options.map(option => {
            const contentCla = classnames({
              [`${prefixCls}-content-line`]: true,
              'active': option.key === value
            })
            return (
              <div 
                className={contentCla} 
                key={`${option.key}_${randomkey}`}
                onClick={() => this.onChange(option)}
              >
                <div className={`${prefixCls}-content-line-item`}>{option.showname}</div>
              </div>
            )
          })}
        </div>
      </div>
    )
  }
}
